import queue
import time

from PyQt5.QtCore import QThread, pyqtSignal

import var


class FIFOWorker(QThread):
    current_index_signal = pyqtSignal(int)
    current_pages_signal = pyqtSignal(list)

    output_signal = pyqtSignal(str)

    def __init__(self, mission, num_frames):
        super(FIFOWorker, self).__init__()
        self.page_requests = mission.copy()
        self.num_frames = num_frames
        self.current_index = 0

    def updateIndex(self):
        self.current_index_signal.emit(self.current_index)

    def updatePages(self, input_list):
        self.current_pages_signal.emit(input_list)

    def run(self):
        out_str = ""
        print("receive run")
        page_queue = queue.Queue()
        page_faults = 0  # 置换次数

        g_page_requests = self.page_requests
        for page in g_page_requests:  # 依次请求页面
            time.sleep(var.time_split)
            print("页面队列", end='')
            t = list(page_queue.queue)
            self.updatePages(t)
            if page in list(t):  # 如果页面已经在队列中，不需要进行任何操作
                pass
            elif page_queue.qsize() < self.num_frames:  # 如果页面不在队列中, 且队列未满，将页面添加到队列末尾
                page_queue.put(page)
                self.current_index += 1
                self.updateIndex()
            else:  # 如果页面队列已满，则移除最先到来的
                page_queue.get()
                page_queue.put(page)
                self.current_index += 1
                self.updateIndex()

                page_faults = page_faults + 1  # 置换次数
                out_str += f"下标 {self.current_index - 1} 发生页面置换\n"
                self.output_signal.emit(out_str)

            self.page_requests = self.page_requests[1:]  # 删除需求队列中的第一个
        t = list(page_queue.queue)
        self.updatePages(t)
        out_str += f"运行结束\n总页面置换次数 {page_faults}"
        self.output_signal.emit(out_str)
        print("finish")
